package com.hongxun.project.assets.pTask.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.hongxun.common.utils.StringUtils;
import com.hongxun.common.utils.text.Convert;
import com.hongxun.project.assets.bByq.domain.BByq;
import com.hongxun.project.assets.bByq.service.IBByqService;
import com.hongxun.project.assets.bDivice.domain.BDivice;
import com.hongxun.project.assets.bDivice.mapper.BDiviceMapper;
import com.hongxun.project.assets.bDivice.service.IBDiviceService;
import com.hongxun.project.assets.bMaterial.domain.BMaterial;
import com.hongxun.project.assets.bMaterial.service.IBMaterialService;
import com.hongxun.project.assets.iBoxes.domain.IBoxes;
import com.hongxun.project.assets.iBoxes.service.IIBoxesService;
import com.hongxun.project.assets.iCablePit.domain.ICablePit;
import com.hongxun.project.assets.iCablePit.service.IICablePitService;
import com.hongxun.project.assets.iDevice.domain.IDevice;
import com.hongxun.project.assets.iDevice.service.IIDeviceService;
import com.hongxun.project.assets.iJointPole.service.IIJointPoleService;
import com.hongxun.project.assets.iLine.domain.ILine;
import com.hongxun.project.assets.iLine.service.IILineService;
import com.hongxun.project.assets.iMaterial.domain.IMaterial;
import com.hongxun.project.assets.iMaterial.service.IIMaterialService;
import com.hongxun.project.assets.iPicture.domain.IPicture;
import com.hongxun.project.assets.iPicture.service.IIPictureService;
import com.hongxun.project.assets.iPoint.domain.IPoint;
import com.hongxun.project.assets.iPoint.service.IIPointService;
import com.hongxun.project.assets.iPole.domain.IPole;
import com.hongxun.project.assets.iPole.service.IIPoleService;
import com.hongxun.project.assets.iPullLine.domain.IPullLine;
import com.hongxun.project.assets.iPullLine.service.IIPullLineService;
import com.hongxun.project.assets.pBoxes.domain.PBoxes;
import com.hongxun.project.assets.pBoxes.service.IPBoxesService;
import com.hongxun.project.assets.pCablePit.domain.PCablePit;
import com.hongxun.project.assets.pCablePit.service.IPCablePitService;
import com.hongxun.project.assets.pDevice.domain.PDevice;
import com.hongxun.project.assets.pDevice.service.IPDeviceService;
import com.hongxun.project.assets.pJointPole.domain.PJointPole;
import com.hongxun.project.assets.pJointPole.service.IPJointPoleService;
import com.hongxun.project.assets.pMaterial.domain.PMaterial;
import com.hongxun.project.assets.pMaterial.service.IPMaterialService;
import com.hongxun.project.assets.pPicture.domain.PPicture;
import com.hongxun.project.assets.pPicture.service.IPPictureService;
import com.hongxun.project.assets.pPoint.domain.PPoint;
import com.hongxun.project.assets.pPoint.service.IPPointService;
import com.hongxun.project.assets.pPole.domain.PPole;
import com.hongxun.project.assets.pPole.service.IPPoleService;
import com.hongxun.project.assets.pPullLine.domain.PPullLine;
import com.hongxun.project.assets.pPullLine.service.IPPullLineService;
import com.hongxun.project.rest.AppLoginController;
import com.hongxun.project.system.dict.domain.DictData;
import com.hongxun.project.system.dict.service.IDictDataService;
import com.hongxun.project.system.user.domain.User;
import com.hongxun.project.system.user.service.IUserService;
import com.hongxun.project.tool.assets.I2PUtils;
import com.hongxun.project.tool.assets.P2IUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.hongxun.framework.aspectj.lang.annotation.Log;
import com.hongxun.framework.aspectj.lang.enums.BusinessType;
import com.hongxun.project.assets.pTask.domain.PTask;
import com.hongxun.project.assets.pTask.service.IPTaskService;
import com.hongxun.framework.web.controller.BaseController;
import com.hongxun.framework.web.page.TableDataInfo;
import com.hongxun.framework.web.domain.AjaxResult;
import com.hongxun.common.utils.poi.ExcelUtil;

/**
 * 采集任务 信息操作处理
 *
 * @author hongxun
 * @date 2019-03-19
 */
@Controller
@RequestMapping("/assets/pTask")
public class PTaskController extends BaseController {
    private String prefix = "assets/pTask";

    @Autowired
    private IPTaskService pTaskService;
    @Autowired
    private IILineService iLineService;
    @Autowired
    private IBByqService bByqService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IPPointService pPointService;
    @Autowired
    private IPPictureService pPictureService;
    @Autowired
    private IPPullLineService pPullLineService;
    @Autowired
    private IIPictureService iPictureService;
    @Autowired
    private IBMaterialService bMaterialService;
    @Autowired
    private IPMaterialService pMaterialService;
    @Autowired
    private IPDeviceService pDeviceService;
    @Autowired
    private IDictDataService dictDataService;
//    @Autowired
//    private BDiviceMapper bDiviceMapper;


    @Autowired
    IPBoxesService ipBoxesService;
    @Autowired
    private IIBoxesService iBoxesService;
    @Autowired
    IPCablePitService ipCablePitService;
    @Autowired
    IPDeviceService ipDeviceService;
    @Autowired
    IPMaterialService ipMaterialService;
    @Autowired
    IPPointService ipPointService;
    @Autowired
    IPPoleService ipPoleService;
    @Autowired
    IPPullLineService ipPullLineService;
    @Autowired
    IPPictureService ipPictureService;
    @Autowired
    IPJointPoleService ipJointPoleService;



    @Autowired
    IIBoxesService iiBoxesService;
    @Autowired
    IICablePitService iiCablePitService;
    @Autowired
    IIDeviceService iiDeviceService;
    @Autowired
    IIMaterialService iiMaterialService;
    @Autowired
    IIPointService iiPointService;
    @Autowired
    IIPoleService iiPoleService;
    @Autowired
    IBDiviceService bDiviceService;
    @Autowired
    IIPullLineService iiPullLineService;
    @Autowired
    IIPictureService iiPictureService;
    @Autowired
    IIJointPoleService iiJointPoleService;
    @Autowired
    private IICablePitService iCablePitService;


    @RequiresPermissions("assets:pTask:view")
    @GetMapping()
    public String pTask() {
        return prefix + "/pTask";
    }

    /**
     * 任务详情页面跳转
     *
     * @return
     */
    @GetMapping("/pTaskDetails/{id}")
    public String pTaskDetails(@PathVariable("id") String id, ModelMap modelMap) {
        modelMap.put("taskId", id);
        return prefix + "/pTaskDetails";
    }



    /**
     * 任务详情--点位杆塔编辑页面跳转
     * @return
     */
    @GetMapping("/showGt/{id}/{taskId}")
    public String showGt(@PathVariable("id") String id ,@PathVariable("taskId") String taskId , ModelMap modelMap)
    {
        modelMap.put("pointId",id);					// 点位ID
        modelMap.put("taskId",taskId);				// 任务ID
        return prefix + "/GtDetailed";
    }

    /**
     * 任务详情--分支箱编辑页面跳转
     * @return
     */
    @GetMapping("/showFzx/{id}/{taskId}")
    public String showFzx(@PathVariable("id") String id ,@PathVariable("taskId") String taskId , ModelMap modelMap)
    {
        modelMap.put("pointId",id);					// 点位ID
        modelMap.put("taskId",taskId);				// 任务ID
        return prefix + "/FzxDetailed";
    }

    /**
     * 任务详情--下户点编辑页面跳转
     * @return
     */
    @GetMapping("/showXhd/{id}/{taskId}")
    public String showXhd(@PathVariable("id") String id ,@PathVariable("taskId") String taskId , ModelMap modelMap)
    {
        modelMap.put("pointId",id);					// 点位ID
        modelMap.put("taskId",taskId);				// 任务ID
        return prefix + "/XhdDetailed";
    }

    /**
     * 任务详情--变压器编辑页面跳转
     * @return
     */
    @GetMapping("/showByq/{id}/{taskId}")
    public String showByq(@PathVariable("id") String id ,@PathVariable("taskId") String taskId , ModelMap modelMap)
    {
        modelMap.put("pointId",id);					// 点位ID
        modelMap.put("taskId",taskId);				// 任务ID
        return prefix + "/byqDetailed";
    }


    /**
     * 任务详情--点位表箱编辑页面跳转
     * @return
     */
    @GetMapping("/showBx/{id}/{taskId}")
    public String showBx(@PathVariable("id") String pointId ,@PathVariable("taskId") String taskId , ModelMap modelMap)
    {
        PBoxes pBoxes = new PBoxes();
        pBoxes.setPId(pointId);
        pBoxes.setDatastate("删除");
        List<PBoxes> list = ipBoxesService.selectPBoxesList(pBoxes);
        for (PBoxes boxes : list) {
            modelMap.put("Id",boxes.getId());				// ID
            modelMap.put("pointId",boxes.getPId());			// 点位ID
        }
        modelMap.put("taskId",taskId);

        return prefix + "/BoxesDetailed";
    }


    /**
     * 任务详情--点位电缆井编辑页面跳转
     * @return
     */
    @GetMapping("/showDlj/{id}/{taskId}")
    public String showDlj(@PathVariable("id") String pointId ,@PathVariable("taskId") String taskId , ModelMap modelMap)
    {
        PCablePit pCablePit = new PCablePit();
        pCablePit.setPId(pointId);
        pCablePit.setDatastate("删除");
        List<PCablePit> list = ipCablePitService.selectPCablePitList(pCablePit);
        for (PCablePit pablePit : list) {
            modelMap.put("Id",pablePit.getId());			// ID
            modelMap.put("pointId",pablePit.getPId());		// 点位ID
        }
        modelMap.put("taskId",taskId);

        return prefix + "/CablePitDetailed";
    }


    /**
     * 任务详情--交叉跨越编辑页面跳转
     * @return
     */
    @GetMapping("/showJcky/{id}/{taskId}")
    public String showJcky(@PathVariable("id") String id , @PathVariable("taskId") String taskId ,ModelMap modelMap)
    {
        modelMap.put("pointId",id);					// 点位ID
        modelMap.put("taskId",taskId);
        return prefix + "/CrossoverDetailed";
    }

    /**
     * 地理走向图跳转
     *
     * @param id
     * @param modelMap
     * @return
     */
    @GetMapping("/pTaskMap/{id}")
    public String pTaskMap(@PathVariable("id") String id, ModelMap modelMap) {
        modelMap.put("taskId", id);
        PPoint pPoint = new PPoint();
        pPoint.setTaskId(id);
        pPoint.setDatastate("删除");
        List<PPoint> pPointList = pPointService.selectPPointList(pPoint);
        int ios = 0 ;
        for (PPoint point : pPointList) {
            if(ios == 0){
                modelMap.put("lgt_task", point.getLgt());
                modelMap.put("lat_task", point.getLat());
            }
            ++ios;
        }
        return prefix + "/taskMap";
    }


    /**
     * 单机点位后，进行点位数据和照片查看
     */
    @PostMapping("/showPointInfo")
    @ResponseBody
    public List<Map<String, Object>> showPointInfo(@RequestParam Map<String, Object> map, ModelMap modelMap) {

        List<Map<String, Object>> pointList = new ArrayList();
        //  通过点位id获取对应点位信息和照片
        String pointId = map.get("id").toString();
        String taskId = map.get("taskId").toString();
        PPoint pPoint = pPointService.selectPPointByIdForState(pointId, taskId);
        PPicture pPictures = new PPicture();
        pPictures.setPId(pointId);
        pPictures.setDatastate("删除");
        List<PPicture> pPictureList = pPictureService.selectPPictureList(pPictures);
        Map<String, Object> map1;
        for (PPicture pPicture : pPictureList) {
            map1 = new HashMap<>();
            map1.put("pPicture", pPicture);
            pointList.add(map1);
        }
        modelMap.put("pPoint", pPoint);
        pointList.add(modelMap);

        return pointList;
    }




    /**
     * 	材料选择页面
     * @return
     */
    @GetMapping("getAllMaterial")
    public String getAllMaterial(){
        return prefix+"/MaterialDetailed";
    }


    /**
     * 	设备选择页面
     * @return
     */
    @GetMapping("getAllDivicel")
    public String getAllDivicel(){
        return prefix+"/DeviceDetailed";
    }



    /**
     *  添加材料
     *
     * @param
     * @return
     */
    @PostMapping("addMaterial")
    @ResponseBody
    public AjaxResult addMaterial(@RequestParam Map<String , Object> objectMap){
        String materialIds = objectMap.get("materialId").toString();	//	材料ID
        String pointId = objectMap.get("pointId").toString();			//	点位ID
        String lineId = objectMap.get("lineId").toString();				//	低压线路ID
        String byqId = objectMap.get("byqId").toString();				//	所属变压器ID
        String taskId = objectMap.get("taskId").toString();				//	任务ID
        String[] materialId = materialIds.split(",");

        PMaterial pMaterial = new PMaterial();
        int i = 0;
        for (String s : materialId) {
            //	从材料库查询所选材料
            BMaterial bMaterial = bMaterialService.selectBMaterialById(s);
            //	将查询出对应的材料添加到点位材料采集数据库

            pMaterial.setBMaterialId(bMaterial.getId());
            pMaterial.setPointId(pointId);
            pMaterial.setLineId(lineId);
            pMaterial.setByqId(byqId);
            pMaterial.setBigType(bMaterial.getBigType());
            pMaterial.setMidType(bMaterial.getMidType());
            pMaterial.setLable(bMaterial.getLable());
            pMaterial.setName(bMaterial.getName());
            pMaterial.setModle(bMaterial.getModle());
            pMaterial.setCode(bMaterial.getCode());
            pMaterial.setUnit(bMaterial.getUnit());
            pMaterial.setPrice(bMaterial.getPrice());
            pMaterial.setCount(BigDecimal.ONE);
            pMaterial.setTechParameter(bMaterial.getTechParameter());
            pMaterial.setReleaseStatus(bMaterial.getReleaseStatus());
            pMaterial.setAddUser(Integer.parseInt(getUserId().toString()));
            pMaterial.setAddDate(new Date());
            pMaterial.setDatastate("新增");
            pMaterial.setTaskId(taskId);

            i = pMaterialService.insertPMaterial(pMaterial);

        }

        return toAjax(i);
    }



    /**
     *  添加设备
     *
     * @param
     * @return
     */
    @PostMapping("addDivice")
    @ResponseBody
    public AjaxResult addDivice(@RequestParam Map<String , Object> objectMap){
        String devicelIds = objectMap.get("divicelId").toString();		//	设备ID
        String pointId = objectMap.get("pointId").toString();			//	点位ID
        String lineId = objectMap.get("lineId").toString();				//	低压线路ID
        String byqId = objectMap.get("byqId").toString();				//	所属变压器ID
        String taskId = objectMap.get("taskId").toString();				//	任务ID
        String[] devicelId = devicelIds.split(",");

        PDevice pDevice = new PDevice();
        int i = 0;
        for (String s : devicelId) {
            //	从设备库查询所选设备
            BDivice bDivice = bDiviceService.selectBDiviceById(s);
            //	将查询出对应的设备添加到设备采集数据库

            pDevice.setBDiveceId(bDivice.getId());
            pDevice.setPointId(pointId);
            pDevice.setLineId(lineId);
            pDevice.setByqId(byqId);
            pDevice.setBigType(bDivice.getBigType());
            pDevice.setMidType(bDivice.getMidType());
            pDevice.setLable(bDivice.getLable());
            pDevice.setName(bDivice.getName());
            pDevice.setModle(bDivice.getModle());
            pDevice.setCode(bDivice.getCode());
            pDevice.setUnit(bDivice.getUnit());
            pDevice.setPrice(bDivice.getPrice());
            pDevice.setTechParameter(bDivice.getTechParameter());
            pDevice.setAddUser(Integer.parseInt(getUserId().toString()));
            pDevice.setAddDate(new Date());
            pDevice.setDatastate("新增");
            pDevice.setTaskId(taskId);

            i = pDeviceService.insertPDevice(pDevice);

        }

        return toAjax(i);
    }





    /**
     * 采集人、审核人列表
     *
     * @return
     */
    @GetMapping("/userAdd")
    public String userAdd() {
        return prefix + "/userAdd";
    }

    /**
     * 采集人、审核人修改时，数据回显
     *
     * @param map
     * @param mmap
     * @return
     */
    @GetMapping("/userUpdate")
    public String userUpdate(@RequestParam Map<String, Object> map, ModelMap mmap) {
        PTask pTask = pTaskService.selectPTaskById(map.get("id").toString());
        pTask.setByqName(map.get("attrName").toString());
        mmap.put("pTask", pTask);
        return prefix + "/userUpdate";
    }


    @PostMapping("/listUsers")
    @ResponseBody
    public TableDataInfo listUsers(User user)
    {
        startPage();
        List<User> list = userService.selectUserList(user);
        return getDataTable(list);
    }


    /**
     * 请选择人员
     *
     * @param map
     * @param
     * @return
     */
    @PostMapping("/placeChooseUser")
    @ResponseBody
    public List<Map<String, Object>> placeChooseUser(@RequestParam Map<String, Object> map) {
        String id = map.get("id").toString();
        String name = map.get("name").toString();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        PTask pTask = pTaskService.selectPTaskById(id);
        // TODO: 2019/3/25  通过已选人员与所有人员做比较，筛选出待选人员
        List<User> userList = userService.selectUserList(new User());
        User user = new User();
        // 采集人元id
        if (name.equals("采集人")) {
            String[] userIdCj = pTask.getUseId().split(",");
            for (int i1 = 0; i1 < userIdCj.length; i1++) {
                for (int i = 0; i < userList.size(); i++) {
                    if (userList.get(i).getUserId().toString().equals(userIdCj[i1])) {
                        userList.remove(i);
                    }
                }
            }
            for (User user1 : userList) {
                Map<String, Object> mapObj = new HashMap<>();
                mapObj.put("useId", user1.getUserId());
                mapObj.put("useName", user1.getUserName());
                list.add(mapObj);
            }
        } else {
            String[] userIdSh = pTask.getAuditorId().split(",");
            for (int i1 = 0; i1 < userIdSh.length; i1++) {
                for (int i = 0; i < userList.size(); i++) {
                    if (userList.get(i).getUserId().toString().equals(userIdSh[i1])) {
                        userList.remove(i);
                    }
                }
            }
            for (User user1 : userList) {
                Map<String, Object> mapObj = new HashMap<>();
                mapObj.put("useId", user1.getUserId());
                mapObj.put("useName", user1.getUserName());
                list.add(mapObj);
            }
        }

        return list;
    }


    /**
     * 已选择人员
     *
     * @param map
     * @param
     * @return
     */
    @PostMapping("/AlreadyChooseUser")
    @ResponseBody
    public List<Map<String, Object>> AlreadyChooseUser(@RequestParam Map<String, Object> map) {
        String id = map.get("id").toString();
        String name = map.get("name").toString();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        PTask pTask = pTaskService.selectPTaskById(id);
        User user = new User();
        // 采集人元id
        if (name.equals("采集人")) {
            String[] userIdCj = pTask.getUseId().split(",");
            for (String s : userIdCj) {
                Map<String, Object> mapObj = new HashMap<>();
                user = userService.selectUserById(Long.parseLong(s));
                mapObj.put("useId", s);
                mapObj.put("useName", user.getUserName());
                list.add(mapObj);
            }
        } else {
            String[] userIdCj = pTask.getAuditorId().split(",");
            for (String s : userIdCj) {
                Map<String, Object> mapObj = new HashMap<>();
                user = userService.selectUserById(Long.parseLong(s));
                mapObj.put("useId", s);
                mapObj.put("useName", user.getUserName());
                list.add(mapObj);
            }
        }
        return list;
    }


    /**
     * 任务地理走向图--点位信息
     *
     * @param objectMap
     * @return
     */
    @PostMapping("linePoint")
    @ResponseBody
    public List<PPoint> linePoint(@RequestParam Map<String, Object> objectMap) {

        //  通过任务ID查询所属任务点位
        String taskId = objectMap.get("taskId").toString();
        PPoint pPoint = new PPoint();
        pPoint.setTaskId(taskId);
        pPoint.setDatastate("删除");
        List<PPoint> pPointList = pPointService.selectPPointList(pPoint);
        List<PPoint> pPointListss = new ArrayList<>();
        int iost = 0;
        for (PPoint point : pPointList) {

            //  线路名称
//            StringBuffer sb = new StringBuffer();

            /*
                如果当前杆塔是同杆点位，则通过上联点位查询对应的同杆架设点位，
                再通过同杆架设点位的同杆架设组ID的查询对应id的点位作为替换
            */
            /*if(!point.getType().equals("同杆架设")){
                if(point.getType().equals("杆塔") && point.getIsPole().equals("是") && point.getUpId() != null){
                    PPoint pPoint1 = pPointService.selectPPointByIdForState(point.getUpId(),taskId);
                    PPoint pPoint21 = new PPoint();
                    pPoint21.setLgt(point.getLgt());
                    pPoint21.setLat(point.getLat());
                    List<PPoint> pPoints = pPointService.selectPPointList(pPoint21);
                    if(pPoints.size() > 0){
                        for (PPoint pPoint2 : pPoints) {
                            ILine iLine1 = iLineService.selectILineById(pPoint2.getLineId());
                            sb.append(iLine1.getName());
                            sb.append(",");
                        }
                    }

                    String lName = sb.substring(0,sb.lastIndexOf(","));
                    point.setLineName(lName.toString());
                    if(pPoint1.getType().equals("同杆架设")){
                        PPoint pPoint2 = pPointService.selectPPointByIdForState(pPoint1.getPoleId(),taskId);
                        point.setUpId(pPoint2.getId());
                        pPointListss.add(point);
                    }else{
                        pPointListss.add(point);
                    }
                }else{
                    ++iost;
                    if(iost % 2 == 0){
                        ILine iLine = iLineService.selectILineById(point.getLineId());
                        if(iLine !=null) point.setLineName(iLine.getName());
                    }
                    pPointListss.add(point);
                }
            }*/



            iost++;

            if(point.getType().equals("同杆架设")){
                PPoint iPoint2 = pPointService.selectPPointByIdForState(point.getPoleId(),taskId);
                ILine iLine = iLineService.selectILineById(point.getLineId());
                ILine iLine1 = iLineService.selectILineById(iPoint2.getLineId());
                if (iLine != null && iLine1 != null){
                    String xlw = iLine.getName()+","+iLine1.getName();
                    point.setLineName(xlw);
                }
                point.setCode(iPoint2.getCode());
            }else{
                if(!(point.getType().equals("杆塔") && point.getIsPole().equals("是"))){
                    if(iost % 3 == 0 ){
                        ILine iLine = iLineService.selectILineById(point.getLineId());
                        if(iLine !=null) point.setLineName(iLine.getName());
                    }

                }

            }



        }


        for (PPoint point : pPointList) {
            if (point.getPullNum() != null) {
                if (point.getPullNum() > 0) {
                    PPullLine pPullLine = new PPullLine();
                    pPullLine.setPId(point.getId());
                    pPullLine.setDatastate("删除");
                    List<PPullLine> pullLineList = pPullLineService.selectPPullLineList(pPullLine);
                    for (PPullLine pullLine : pullLineList) {
                        point.setLxLgt(pullLine.getLgt());
                        point.setLxLat(pullLine.getLat());
                    }
                }
            }
//            if(!point.getType().equals("同杆架设")){
//                pPointList2.add(point);
//            }
        }

        return pPointList;
    }


    /**
     * 查询采集任务列表
     */
    @RequiresPermissions("assets:pTask:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(PTask pTask) {
        startPage();
        List<PTask> list = pTaskService.selectPTaskList(pTask);
        for (PTask task : list) {
            String[] userId = task.getUseId().split(",");
            StringBuffer sbf = new StringBuffer();
            for (String s : userId) {
                User u = userService.selectUserById(Long.parseLong(s));
                sbf.append(u.getUserName());
                sbf.append(",");
            }
            String s1 = sbf.substring(0, sbf.length() - 1);
            task.setUseName(s1);

            String linesNameByqId = iLineService.getLinesNameByqId(task.getByqId());
            if (StringUtils.isEmpty(linesNameByqId)) task.setLineName("暂无线路");
            else task.setLineName(linesNameByqId);
        }
        return getDataTable(list);
    }


    /**
     *  获取照片
     */
    @GetMapping("getPicture/{pointId}/{taskId}")
    public String getPicture(@PathVariable("pointId") String id ,@PathVariable("taskId") String taskId, ModelMap modelMap){
        modelMap.put("pointId",id);
        modelMap.put("taskId",taskId);
        return prefix+"/picture";
    }

    @PostMapping("getssPicture")
    @ResponseBody
    public List getssPicture(@RequestParam String pointId , @RequestParam String taskId){
        PPicture pPicture = new PPicture();
        pPicture.setPId(pointId);
        pPicture.setTaskId(taskId);
        pPicture.setDatastate("删除");
        List<PPicture> pPictureList = pPictureService.selectPPictureList(pPicture);
        List<DictData> dictDataList = dictDataService.selectDictDataForSort(pointId);
        //  排序
        if(pPictureList.size() > 0){
            for (PPicture picture : pPictureList) {
                for (DictData dictData : dictDataList) {
                    if(picture.getType().equals(dictData.getDictLabel())){
                        picture.setSort(dictData.getDictSort().intValue());
                        pPictureService.updatePPicture(picture);
                    }
                }
            }
        }
        List<PPicture> pPictureListss = pPictureService.selectListOrderByType(pPicture);

        return pPictureListss;
    }



    /**
     * 导出采集任务列表
     */
    @RequiresPermissions("assets:pTask:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(PTask pTask) {
        List<PTask> list = pTaskService.selectPTaskList(pTask);
        ExcelUtil<PTask> util = new ExcelUtil<PTask>(PTask.class);
        return util.exportExcel(list, "pTask");
    }

    /**
     * 新增采集任务
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存采集任务
     */
    @RequiresPermissions("assets:pTask:add")
    @Log(title = "采集任务", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(PTask pTask) {
        pTask.setCreateId(getUserId().toString());
        pTask.setReleaseTime(new Date());
        pTask.setTaskStatus("新增");
        //  查询该变压器下所有的线路
        ILine iLine = new ILine();
        iLine.setByqId(pTask.getByqId());
        List<ILine> iLines = iLineService.selectILineList(iLine);
        String ios = null;
        StringBuffer sb = new StringBuffer();
        if(iLines.size() > 0){
            for (ILine line : iLines) {
                sb.append(line.getId());
                sb.append(",");
            }
            ios = sb.substring(0,sb.lastIndexOf(","));
            pTask.setLineId(ios);
        }

        return toAjax(pTaskService.insertPTask(pTask));
    }

    /**
     * 修改采集任务
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap) {
        PTask pTask = pTaskService.selectPTaskById(id);
        BByq bByq = bByqService.selectBByqById(pTask.getByqId());
        ILine iLine = new ILine();
        String lie = "";
        if(pTask.getLineId() != null){
            String[] lineId = pTask.getLineId().split(",");
            StringBuffer strLine = new StringBuffer();
            for (String s : lineId) {
                iLine = iLineService.selectILineById(s);
                strLine.append(iLine.getName());
                strLine.append(",");
            }
            lie = strLine.substring(0, strLine.length() - 1);
        }

//        ILine iLine = iLineService.selectILineById(pTask.getLineId());

        //	采集人
        String[] userIdCj = pTask.getUseId().split(",");
        StringBuffer sbcj = new StringBuffer();
        User user = new User();
        for (String s : userIdCj) {
            user = userService.selectUserById(Long.parseLong(s));
            sbcj.append(user.getUserName());
            sbcj.append(",");
        }
        String cj = sbcj.substring(0, sbcj.length() - 1);

        // 审核人
        String[] userIdSh = pTask.getAuditorId().split(",");
        StringBuffer sbsh = new StringBuffer();
        for (String idSh : userIdSh) {
            user = userService.selectUserById(Long.parseLong(idSh));
            sbsh.append(user.getUserName());
            sbsh.append(",");
        }
        String sh = sbsh.substring(0, sbsh.length() - 1);

        pTask.setUseName(cj);
        pTask.setAuditorName(sh);
        pTask.setLineName(lie);
        pTask.setByqName(bByq.getName());
        mmap.put("pTask", pTask);
        mmap.put("byqId", pTask.getByqId());
        return prefix + "/edit";
    }

    /**
     *  任务选择线路
     *
     * @return
     */
    @GetMapping("/chooseLine")
    public String chooseLine(PTask pTask , ModelMap modelMap)
    {
        modelMap.put("byqId",pTask.getByqId());
        return prefix + "/chooseLine";
    }




    /**
     * 修改保存采集任务
     */
    @RequiresPermissions("assets:pTask:edit")
    @Log(title = "采集任务", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(PTask pTask) {
        return toAjax(pTaskService.updatePTask(pTask));
    }

    /**
     * 删除采集任务
     */
    @RequiresPermissions("assets:pTask:remove")
    @Log(title = "采集任务", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        String[] idArr = Convert.toStrArray(ids);
        List<PPoint> pPoints = new ArrayList<>();
        for (String s : idArr) {
            PPoint pPoint = new PPoint();
            pPoint.setDatastate("删除");
            pPoint.setTaskId(s);
            pPoints = pPointService.selectPPointList(pPoint);
            if (pPoints.size() != 0){
                return error("该任务下有点位信息，不能删除！");
            }
        }
        return toAjax(pTaskService.deletePTaskByIds(ids));
    }

    @GetMapping("/file/{id}")
    @ResponseBody
    public AjaxResult taskFile(@PathVariable("id") String id) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(9);//线程计数器
        ExecutorService executorService = Executors.newFixedThreadPool(20);//获取线程池
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                PBoxes pBoxes = new PBoxes();
                pBoxes.setTaskId(id);
                List<PBoxes> p = ipBoxesService.selectPBoxesList(pBoxes);
                iiBoxesService.file(p);
                latch.countDown();
            }
        });
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                PCablePit pBoxes = new PCablePit();
                pBoxes.setTaskId(id);
                List<PCablePit> p = ipCablePitService.selectPCablePitList(pBoxes);
                iiCablePitService.file(p);
                latch.countDown();
            }
        });
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                PDevice pBoxes = new PDevice();
                pBoxes.setTaskId(id);
                List<PDevice> p = ipDeviceService.selectPDeviceList(pBoxes);
                iiDeviceService.file(p);
                latch.countDown();
            }
        });
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                PJointPole pBoxes = new PJointPole();
                pBoxes.setTaskId(id);
                List<PJointPole> p = ipJointPoleService.selectPJointPoleList(pBoxes);
                iiJointPoleService.file(p);
                latch.countDown();
            }
        });
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                PMaterial pBoxes = new PMaterial();
                pBoxes.setTaskId(id);
                List<PMaterial> p = ipMaterialService.selectPMaterialList(pBoxes);
                iiMaterialService.file(p);
                latch.countDown();
            }
        });
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                PPicture pBoxes = new PPicture();
                pBoxes.setTaskId(id);
                List<PPicture> p = ipPictureService.selectPPictureList(pBoxes);
                iiPictureService.file(p);
                latch.countDown();
            }
        });
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                PPoint pBoxes = new PPoint();
                pBoxes.setTaskId(id);
                List<PPoint> p = ipPointService.selectPPointList(pBoxes);
                iiPointService.file(p);
                latch.countDown();
            }
        });
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                PPole pBoxes = new PPole();
                pBoxes.setTaskId(id);
                List<PPole> p = ipPoleService.selectPPoleList(pBoxes);
                iiPoleService.file(p);
                latch.countDown();
            }
        });
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                PPullLine pBoxes = new PPullLine();
                pBoxes.setTaskId(id);
                List<PPullLine> p = ipPullLineService.selectPPullLineList(pBoxes);
                iiPullLineService.file(p);
                latch.countDown();
            }
        });
        latch.await();
        executorService.shutdown();
        PTask task = pTaskService.selectPTaskById(id);
        task.setTaskStatus("归档");
        pTaskService.updatePTask(task);
        return success();
    }

    @GetMapping("/release/{id}")
    @ResponseBody
    public AjaxResult release(@PathVariable("id") String id) throws InterruptedException {
        PTask task = pTaskService.selectPTaskById(id);
        task.setTaskStatus("采集");
        pTaskService.updatePTask(task);
        copyData2Task(task);
        return success();
    }

    @GetMapping("/end/{id}")
    @ResponseBody
    public AjaxResult end(@PathVariable("id") String id) {
        PTask task = pTaskService.selectPTaskById(id);
        task.setTaskStatus("审核");
        pTaskService.updatePTask(task);
        return success();
    }



    public void copyData2Task(PTask task) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(20);//获取线程池
        CountDownLatch latch = new CountDownLatch(8);//线程计数器
        IPoint iPoint = new IPoint();
        iPoint.setByqId(task.getByqId());//根据变压器获取线路IDS
        final List<IPoint> iPoints =iiPointService.selectIPointList(iPoint);
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < iPoints.size(); i++) {
            stringBuffer.append(iPoints.get(i).getId());
            if (i != iPoints.size() - 1) stringBuffer.append(",");
        }
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                ipPointService.insertOrReplaceOrDelete(I2PUtils.getPoint(task.getId(), iPoints));
                latch.countDown();
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                IBoxes iBoxes = new IBoxes();
                iBoxes.setPId(stringBuffer.toString());
                ipBoxesService.insertOrReplaceOrDelete(I2PUtils.getBoxes(task.getId(),
                        iiBoxesService.selectIBoxesList(iBoxes)));
                latch.countDown();
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                ICablePit iCablePit = new ICablePit();
                iCablePit.setPId(stringBuffer.toString());
                ipCablePitService.insertOrReplaceOrDelete(I2PUtils.getCablePit(task.getId(),
                        iiCablePitService.selectICablePitList(iCablePit)));
                latch.countDown();
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                IDevice iCablePit = new IDevice();
                iCablePit.setPointId(stringBuffer.toString());
                ipDeviceService.insertOrReplaceOrDelete(I2PUtils.getDevice(task.getId(),
                        iiDeviceService.selectIDeviceList(iCablePit)));
                latch.countDown();
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                IMaterial iCablePit = new IMaterial();
                iCablePit.setPointId(stringBuffer.toString());
                ipMaterialService.insertOrReplaceOrDelete(I2PUtils.getMaterial(task.getId(),
                        iiMaterialService.selectIMaterialList(iCablePit)));
                latch.countDown();
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                IPole iCablePit = new IPole();
                iCablePit.setPId(stringBuffer.toString());
                ipPoleService.insertOrReplaceOrDelete(I2PUtils.getPole(task.getId(),
                        iiPoleService.selectIPoleList(iCablePit)));
                latch.countDown();
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                IPicture iCablePit = new IPicture();
                iCablePit.setPId(stringBuffer.toString());
                ipPictureService.insertOrReplaceOrDelete(I2PUtils.getPicture(task.getId(),
                        iiPictureService.selectIPictureList(iCablePit)));
                latch.countDown();
            }
        });
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                IPullLine iCablePit = new IPullLine();
                iCablePit.setPId(stringBuffer.toString());
                ipPullLineService.insertOrReplaceOrDelete(I2PUtils.getPullLine(task.getId(),
                        iiPullLineService.selectIPullLineList(iCablePit)));
                latch.countDown();
            }
        });
        latch.await();
        executorService.shutdown();
    }



}
